package yc.web.servlets;

import redis.clients.jedis.Jedis;
import yc.bean.PageBean;
import yc.bean.Resfood;
import yc.bean.User;
import yc.dao.DBHelper;
import yc.dao.RedisHelper;
import yc.utils.YcConstants;
import yc.web.ResfoodBiz;
import yc.web.model.JsonModel;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

@WebServlet("/resfood.action")
public class ResfoodServlet extends BaseServlet{
    //分页查询
    //参数:&page=1&pagesize=5&sortby=realprice&realprice&sort=asc
    protected void findFoodsByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        JsonModel jm = new JsonModel();
        PageBean pb=null;
        try {
            //去前端分页的参数
            pb=super.parseObjectFromRequest1(req,PageBean.class);
            //调用业务层，完成分页查询...
            ResfoodBiz rb=new ResfoodBiz();
            pb=rb.findByPage(pb);
            HttpSession session=req.getSession();
            session.setAttribute("foodList",pb.getDataset());//将菜单保存到session中
            jm.setCode(1);
            jm.setObj(pb);
        } catch (Exception e) {
           e.printStackTrace();
           jm.setCode(0);
           jm.setError("分页查询失败");
        }
        super.writeJson(jm,resp);
    }
    protected void findAllFoods(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        JsonModel jm = new JsonModel();
        String sql="select * from resfood";
        List<Resfood> list = db.select(Resfood.class,sql);
        HttpSession session=req.getSession();
        //Tomcat提供的缓存 =》redis做缓存
        session.setAttribute("foodList",list);
        jm.setCode(1);
        jm.setObj(list);
        super.writeJson(jm,resp);

    }
    protected void traceBrowseFood(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        JsonModel jm = new JsonModel();
        String fid=req.getParameter("fid");
        HttpSession session=req.getSession();
        if (session.getAttribute("user")==null){
            jm.setCode(-1);
            jm.setError("未登录用户不记录足迹");
            super.writeJson(jm,resp);
            return;
        }
        User user=(User) session.getAttribute("user");
        int userid=user.getUserid();
        Date d=new Date();

        Jedis jedis=new Jedis("localhost",6379);
        //先检查，此键的值的长度，如超过你4个，删除4以后得数据。
        long length=jedis.zcard(userid+"_visted");
        if (length>4){
            jedis.zremrangeByRank(userid+"_visted",1,2);
        }
        //在存
        jedis.zadd(userid+"_visted",d.getTime(),fid);
        //ToDo:保存 历史记录 到服务器30天。
        jedis.expire("userid"+"_visted",60*60*24*30);
        //TODO:将所有的tomca中的session都替换成 redis
        jm.setCode(1);
        super.writeJson(jm,resp);

    }
    //登录用户才能获得历史记录
    protected void getHistory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        JsonModel jm = new JsonModel();
        HttpSession session=req.getSession();
        //权限 判断的这一段功能，写到 rightfilter中去
        User user=(User) session.getAttribute("user");
        int userid=user.getUserid();
        Jedis jedis=new Jedis("localhost",6379);
        Set<String>vistedFoodIds=jedis.zrevrange(userid+"_visted",0,4);//获取最近5个访问的菜
        //如果没有访问过任何一个商品则直接返回 code=0
        if (vistedFoodIds==null||vistedFoodIds.size()<=0){
            jm.setCode(0);
            super.writeJson(jm,resp);
            return;
        }
        //采用sql中的 in 拼接多个 商品的查询，减少多个sql语句操作
        StringBuffer sqlbuffer=new StringBuffer("select * from resfood where fid in(");
        for (String fid:vistedFoodIds){
            sqlbuffer.append("?,");
        }
        String sql=sqlbuffer.toString();
        //去掉最后多的
        sql=sql.substring(0,sql.length()-1);
        sql=sql+")";
        System.out.println("执行的sql语句"+sql);//这条语句是拼装出来的最好输出一下。
        DBHelper db=new DBHelper();
        List<Resfood> list=db.select(Resfood.class,sql,vistedFoodIds.toArray());
        jm.setCode(1);
        jm.setObj(list);
        super.writeJson(jm,resp);


    }
    protected void clickPraise(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        JsonModel jm = new JsonModel();
        //取餐号
        Resfood resfood=null;
        try{
            //取出参数 fid
            resfood =super.parseObjectFromRequest1(req,Resfood.class);
            int fid=resfood.getFid();
            HttpSession session=req.getSession();
            //权限判断的这一段功能，写到 rightFilter中去
            User user=(User) session.getAttribute(YcConstants.REUSER);
            int userid=user.getUserid();
            Jedis jedis= RedisHelper.getRedisInstance();
            //菜品号—_praise Set<用户编号>
            if (jedis.sismember(fid+YcConstants.REDIS_FOOD_PRAISE,userid+"")){
                //此用户已经点过这道菜了，再点就是取消
                jedis.srem(fid+YcConstants.REDIS_FOOD_PRAISE,userid+"");
                //用户编号_praise Set<菜品号> 此处也要删除
                jedis.srem(userid+YcConstants.REDIS_PRAISE,fid+"");
            }else {
                //此用户没有对这道菜点过赞
                jedis.sadd(fid+YcConstants.REDIS_FOOD_PRAISE,userid+"");
                //要记录此用户对哪些菜点过菜
                jedis.sadd(userid+YcConstants.REDIS_PRAISE,fid+"");
            }
            //取出最新点赞数
            long praise=jedis.scard(fid+YcConstants.REDIS_FOOD_PRAISE);
            resfood.setPraise(praise);
             jm.setCode(1);
            jm.setObj(resfood);
        }catch (Exception e){
            e.printStackTrace();
            jm.setCode(0);
            jm.setError(e.getMessage());
        }
        super.writeJson(jm,resp);
    }

}
